<template>
	<!-- 查询表单 card -->
	<SearchForm
		:search="search"
		:reset="reset"
		:search-param="searchParam"
		:columns="searchColumns"
		:search-col="searchCol"
		v-show="isShowSearch"
	/>
	<!-- 表格内容 -->
	<div class="card table-main">
		<!-- 表格头部操作按钮 -->
		<div class="table-header">
			<div class="header-button-lf">
				<slot name="tableHeader" :selectedListIds="selectedListIds" :selectedList="selectedList" :isSelected="isSelected"></slot>
			</div>
			<div class="header-button-ri" v-if="toolButton">
				<slot name="toolButton">
					<el-button :icon="Refresh" circle @click="getTableList"></el-button>
					<el-button :icon="Operation" circle v-if="columns.length" @click="openColSetting" />
					<el-button :icon="Search" circle v-if="searchColumns.length" @click="isShowSearch = !isShowSearch" />
				</slot>
			</div>
		</div>
		<!-- 表格主体 -->
		<el-table
			ref="tableRef"
			v-bind="$attrs"
			:data="tableData"
			:border="border"
			:row-key="rowKey"
			@selection-change="selectionChange"
		>
			<!-- 默认插槽 -->
			<slot></slot>
			<template v-for="item in tableColumns" :key="item">
				<!-- selection -->
				<el-table-column
					v-bind="item"
					:align="item.align ?? 'center'"
					reserve-selection
					v-if="item.type == 'selection'"
				></el-table-column>
				<!-- 序号 index -->
				<el-table-column :align="item.align ?? 'center'" v-if="item.type == 'index'" label="序号" :width="item.width">
					<template #default="scope">
						<span>{{ (pageable.current - 1) * pageable.size + scope.$index + 1 }}</span>
					</template>
				</el-table-column>

				<!-- other 循环递归 !item.type: 排除掉index,selection -->
				<TableColumn v-if="!item.type && item.prop" :column="item">
					<!-- $slots可以拿到父组件所传递过来的所有插槽,它是一个对象，key 名对应着插槽名。 -->
					<template v-for="slot in Object.keys($slots)" #[slot]="scope">
						<slot :name="slot" v-bind="scope"></slot>
					</template> </TableColumn
			></template>
			<!-- 插入表格最后一行之后的插槽 -->
			<!-- <template #append>
				<slot name="append"></slot>
			</template> -->
			<!-- 表格无数据情况 -->
			<template #empty>
				<div class="table-empty">
					<slot name="empty">
						<img src="@/assets/images/notData.png" alt="notData" />
						<div>暂无数据</div>
					</slot>
				</div>
			</template>
		</el-table>
		<!-- 分页组件 -->
		<slot name="pagination">
			<Pagination
				v-if="pagination"
				:pageable="pageable"
				:handle-current-change="handleCurrentChange"
				:handle-size-change="handleSizeChange"
			></Pagination>
		</slot>
	</div>
	<!-- 列设置 -->
	<ColSetting v-if="toolButton" ref="colRef" v-model:col-setting="colSetting" />
</template>

<script lang="ts" setup name="ProTable">
import { useTable } from "@/hooks/useTable";
import { TableProps } from "element-plus";
import TableColumn from "./components/TableColumn.vue";
import Pagination from "./components/Pagination.vue";
import ColSetting from "./components/ColSetting.vue";
import SearchForm from "@/components/SearchForm/index.vue";
import { Refresh, Printer, Operation, Search } from "@element-plus/icons-vue";
import { onMounted, provide, ref, watch } from "vue";
import { ColumnProps } from "./interface";
import { BreakPoint } from "../Grid/interface";
import { ElTable } from "element-plus";
import { handleProp } from "@/utils";
import { useSelection } from "@/hooks/useSelection";

interface ProTableProps extends Partial<Omit<TableProps<any>, "data">> {
	columns: ColumnProps[]; // 列配置项
	initParam?: any; //初始化请求参数
	requestApi: (params: any) => Promise<any> | any; // 请求表格数据的api ==> 非必传
	requestAuto?: boolean; // 是否自动执行请求api ==> 非必传 默认true
	requestError?: (params: any) => void; // 表格 api 请求错误监听 ==> 非必传
	dataCallback?: (data: any) => any; // 返回数据的回调函数，可以对数据进行处理 ==> 非必传
	border?: boolean; // 是否带有纵向边框 ===> 非必传，默认为true
	pagination?: boolean; // 是否需要分页组件 ===> 非必传，默认为true
	pageable?: any;
	toolButton?: boolean; // 是否显示表格功能按钮 ==> 非必传（默认为true）
	rowKey?: string; // 行数据的 Key，用来优化 Table 的渲染，当表格数据多选时，所指定的 id ==> 非必传（默认为 id）
	searchCol?: number | Record<BreakPoint, number>; // 表格搜索项 每列占比配置 ==> 非必传 { xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }
}

// 接收父组件参数，配置默认值
const props = withDefaults(defineProps<ProTableProps>(), {
	initParam: {},
	requestAuto: true,
	columns: () => [],
	border: true,
	pagination: true,
	rowKey: "id",
	toolButton: true,
	searchCol: () => ({ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 })
});

// 是否显示搜索模块
const isShowSearch = ref(true);

// 表格 DOM 元素
const tableRef = ref<InstanceType<typeof ElTable>>();

// 表格多选
const { selectionChange, selectedList, selectedListIds, isSelected } = useSelection(props.rowKey);

// 表格操作 Hooks
const { tableData, pageable, searchParam, searchInitParam, getTableList, search, reset, handleSizeChange, handleCurrentChange } =
	useTable(props.requestApi, props.initParam, props.pagination, props.dataCallback, props.requestError);

console.log("pageable: ", pageable.value);

// 清空选中数据列表
const clearSelection = () => tableRef.value!.clearSelection();

// 初始化请求
onMounted(() => {
	props.requestAuto && getTableList();
});

// 监听页面 initParam 改化，重新获取表格数据
watch(() => props.initParam, getTableList, { deep: true });

// 接收 columns 并设置为响应式
const tableColumns = ref<ColumnProps[]>(props.columns);

// 定义 enumMap 存储 enum 值（避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择）
const enumMap = ref(new Map<string, { [key: string]: any }[]>());
provide("enumMap", enumMap);
const setEnumMap = async (col: ColumnProps) => {
	if (!col.enum) return;
	// 如果当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
	if (typeof col.enum !== "function") return enumMap.value.set(col.prop!, col.enum!);
	const { data } = await col.enum();
	enumMap.value.set(col.prop!, data);
};

// 扁平化 columns
const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
	columns.forEach(async col => {
		if (col._children?.length) flatArr.push(...flatColumnsFunc(col._children));
		flatArr.push(col);

		// 给每一项 column 添加 isShow && isFilterEnum 默认属性
		col.isShow = col.isShow ?? true;
		col.isFilterEnum = col.isFilterEnum ?? true;

		// 设置 enumMap
		setEnumMap(col);
	});
	return flatArr.filter(item => !item._children?.length);
};

// flatColumns
const flatColumns = ref<ColumnProps[]>();
flatColumns.value = flatColumnsFunc(tableColumns.value);

// 过滤需要搜索的配置项
const searchColumns = flatColumns.value.filter(item => item.search?.el || item.search?.render);

// 设置搜索表单排序默认值 && 设置搜索表单项的默认值
searchColumns.forEach((column, index) => {
	column.search!.order = column.search!.order ?? index + 2;
	if (column.search?.defaultValue !== undefined && column.search?.defaultValue !== null) {
		searchInitParam.value[column.search.key ?? handleProp(column.prop!)] = column.search?.defaultValue;
		searchParam.value[column.search.key ?? handleProp(column.prop!)] = column.search?.defaultValue;
	}
});

// 排序搜索表单项
searchColumns.sort((a, b) => a.search!.order! - b.search!.order!);

// 列设置，过滤掉不需要设置的列
const colRef = ref();
const colSetting = tableColumns.value!.filter(
	item => !["selection", "index", "expand"].includes(item.type!) && item.prop !== "operation" && item.isShow
);
const openColSetting = () => colRef.value.openColSetting();

defineExpose({
	element: tableRef,
	tableData,
	searchParam,
	pageable,
	getTableList,
	reset,
	clearSelection,
	enumMap,
	isSelected,
	selectedList,
	selectedListIds
});
</script>